﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Handrise.Mobile.BasicModal.GPS;
using System.Windows.Forms;

namespace Handrise.CDCable.Mobile.Business
{
    /// <summary>
    /// 轨迹跟踪服务
    /// </summary>
    public class GPSTraceService
    {
        private GPSService gpsService;

        private Timer getGPSTimer;

        private Timer reportGPSTimer;

        private GPSTrace lastGPSTrace;

        private GpsWorkState gpsWorkState = GpsWorkState.Close;

        private bool datetimeIsSynchriozie = false;

        private Synchronize synchronize = new Synchronize();


        public GPSTraceService()
        {
            gpsService = new GPSService();
            gpsService.OnDeviceStateChange += new DeviceStateChangedEventHandler(gpsService_OnDeviceStateChange);

            getGPSTimer = new Timer();
            getGPSTimer.Interval = 60 * 1000;//60秒采集一次数据
            getGPSTimer.Enabled = false;
            getGPSTimer.Tick += new EventHandler(getGPSTimer_Tick);

            reportGPSTimer = new Timer();
            reportGPSTimer.Interval = 60 * 1000 * 10; //10分钟上报一次数据
            reportGPSTimer.Enabled = false;
            reportGPSTimer.Tick += new EventHandler(reportGPSTimer_Tick);

        }

        public string GPSWorkState
        {
            get{return gpsWorkState.ToString();}
        }

        /// <summary>
        /// GPS采集定时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void getGPSTimer_Tick(object sender, EventArgs e)
        {
            getGPSTimer.Enabled = false;
            try
            {
                double longitude;
                double latitude;
                if (GetGPSInfo(out longitude, out latitude))
                {
                    GPSTrace gpsTrace = new GPSTrace();
                    gpsTrace.GPSTraceID = Guid.NewGuid().ToString();
                    gpsTrace.CollectType = "GPS";
                    gpsTrace.DeviceLocate = "GPS";
                    gpsTrace.CollectDateTime = DateTime.Now;
                    gpsTrace.Latitude = latitude;
                    gpsTrace.Longitude = longitude;
                    gpsTrace.ReportState = "未上报";
                    gpsTrace.UserName = AppLogic.LoginUser.UserName;
                    if (lastGPSTrace != null)
                    {
                        gpsTrace.Distance = gpsService.DistanceOfTwoPoints(lastGPSTrace.Longitude.Value , lastGPSTrace.Latitude.Value , gpsTrace.Longitude.Value , gpsTrace.Latitude.Value );
                    }
                    lastGPSTrace = gpsTrace;
                    AppLogic.dataService.Add<GPSTrace>(gpsTrace);
                }
            }
            catch (Exception ex)
            {
                 
            }

            getGPSTimer.Enabled = true;

        }

        void reportGPSTimer_Tick(object sender, EventArgs e)
        {
            reportGPSTimer.Enabled = false;
            try
            {
                if (AppLogic.netService.CurrentNetType != NetType.None)
                {
                    Synchronize synchronize = new Synchronize();
                    List<GPSTrace> gpsTraces = GetTimerReportGPSTrace(AppLogic.LoginUser.UserName);
                    if (gpsTraces.Count > 0)
                    {
                        synchronize.UploadGPSTrace(gpsTraces);
                    }
                }
            }
            catch (Exception ex)
            {
                
            }

            reportGPSTimer.Enabled = true;
        }

        public event DeviceStateChangeHandler OnDeviceStateChange;

        /// <summary>
        /// GPS定位状态改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void gpsService_OnDeviceStateChange(object sender, GpsWorkState args)
        {
            gpsWorkState = args;

            //如果已经定位，则通过GPS同步一次时间
            if (!datetimeIsSynchriozie && args == GpsWorkState.Position)
            {
                datetimeIsSynchriozie = true;
                GpsInformation gpsInfo = gpsService.GetGpsInformation();
                if(gpsInfo != null)
                {
                    SyncSystemTime syncSystemTime = new SyncSystemTime();
                    syncSystemTime.SetLocalSystemTime(gpsInfo.Time);
                }
            }

            if(OnDeviceStateChange != null)
                OnDeviceStateChange(args.ToString()) ;
        }

        /// <summary>
        /// 计算两个经纬度点之间的距离
        /// </summary>
        /// <param name="longitude1"></param>
        /// <param name="latitude1"></param>
        /// <param name="longitude2"></param>
        /// <param name="latitude2"></param>
        /// <returns></returns>
        public double DistanceOfTwoPoints(double longitude1, double latitude1, double longitude2, double latitude2)
        {
            return gpsService.DistanceOfTwoPoints(longitude1, latitude1, longitude2, latitude2);
        }

        /// <summary>
        /// 启动轨迹跟踪服务
        /// </summary>
        public void Start()
        {
            //开启ＧＰＳ设备
            gpsService.Open();

            //定时采集开启
            getGPSTimer.Enabled = true;

            //开启上报定时
            reportGPSTimer.Enabled = true;
        }

        public void Close()
        {
            //关闭采集定时
            getGPSTimer.Enabled = false;

            //关闭上报定时
            reportGPSTimer.Enabled = false;

            //关闭设备
            gpsService.Close();
        }

        /// <summary>
        /// 获取经纬度信息
        /// </summary>
        /// <param name="longitude"></param>
        /// <param name="latitude"></param>
        /// <returns></returns>
        public bool GetGPSInfo(out double longitude, out double latitude)
        {
            longitude = 0;
            latitude = 0;
            try
            {
                GpsInformation gpsInfo = gpsService.GetGpsInformation();
                if (gpsInfo == null || gpsInfo.Latitude == 0 || gpsInfo.Longitude == 0)
                    return false;

                longitude = gpsInfo.Longitude;
                latitude = gpsInfo.Latitude;
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }


        /// <summary>
        /// 获取需要上报的轨迹信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public List<GPSTrace> GetNeedReportGPSTrace(string userName)
        {
            return AppLogic.dataService.Find<GPSTrace>("ReportState <> '已上报' and UserName ='" + userName + "'", "CollectDateTime desc");
        }

        /// <summary>
        /// 获取定时上报的轨迹信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public List<GPSTrace> GetTimerReportGPSTrace(string userName)
        {
            return AppLogic.dataService.Find<GPSTrace>("ReportState = '未上报' and UserName ='" + userName + "'", "CollectDateTime desc");
        }


        /// <summary>
        /// 获取轨迹信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public List<GPSTrace> GetuserGPSTrace(string userName)
        {
            return AppLogic.dataService.Find<GPSTrace>("UserName ='" + userName + "'", "CollectDateTime desc");
        }

        /// <summary>
        /// 获取日期轨迹信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public List<GPSTrace> GetuserdateGPSTrace(DateTime beginDateTime, DateTime endDateTime, string userName)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("BeginDateTime", beginDateTime);
            parameters.Add("EndDateTime", beginDateTime);
            return AppLogic.dataService.Find<GPSTrace>("UserName ='" + userName + "' and CollectDateTime >=@BeginDateTime and CollectDateTime <= @EndDateTime", "CollectDateTime desc", parameters);
           
         

        }
        /// <summary>
        /// 删除对应用户下的GPS轨迹
        /// </summary>
        /// <param name="userName"></param>
        public void DeleteGPSTraceByUser(string userName)
        {
            AppLogic.dataService.Delete<GPSTrace>("UserName ='" + userName + "'",null);
        }

        /// <summary>
        /// 更新GPS轨迹上报状态
        /// </summary>
        /// <param name="gpsTraces"></param>
        /// <param name="state"></param>
        public void UpdateGPSTraceReportState(DateTime beginDateTime,DateTime endDateTime, string reportState)
        {
            Dictionary<string,object> parameters = new Dictionary<string,object>() ;
            parameters.Add("BeginDateTime",beginDateTime) ;
            parameters.Add("EndDateTime",beginDateTime) ;
            AppLogic.dataService.ExecuteSql("Update GPSTrace Set ReportState = '" + reportState + "' Where CollectDateTime >=@BeginDateTime and CollectDateTime <= @EndDateTime", parameters);
        }

        /// <summary>
        /// 添加一个到位确认的经纬度信息
        /// </summary>
        /// <param name="gpsTrace"></param>
        public void InsertComfireGPS(GPSTrace gpsTrace)
        {
            if (lastGPSTrace != null)
            {
                gpsTrace.Distance = gpsService.DistanceOfTwoPoints(lastGPSTrace.Longitude.Value, lastGPSTrace.Latitude.Value, gpsTrace.Longitude.Value, gpsTrace.Latitude.Value);
            }
            lastGPSTrace = gpsTrace;
            AppLogic.dataService.Add<GPSTrace>(gpsTrace);
        }

        public delegate void DeviceStateChangeHandler(string state);

    }

}
